<?php

namespace Beerus\Modules\BasicSetting\Actions;

use Doraemon\model\DesignerOperatorBind\DesignerOperatorBind;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBindLog;
use Doraemon\model\Operator;
use Illuminate\Http\Request;
use Encore\Admin\Actions\RowAction;

class DesignerOperatorTransfer extends RowAction
{
    public $name = '一键迁移设计师';

    public function handle($id, Request $request)
    {
        $toOperatorId = $request->post('to_operator_id');
        $designerUids = $request->post('designer_uids');
        $toOperatorInfo = Operator::get('*', ['id' => $toOperatorId]);
        if (!$toOperatorInfo) {
            return $this->response()->error('迁移到的运营不存在');
        }
        $where = [
            'operator_id' => $id,
        ];
        if ($designerUids) {
            $errUids = [];
            $designerUids = rtrim($designerUids, ',');
            $where['uid'] = explode(',', $designerUids);
            foreach ($where['uid'] as $designerUid) {
                if (!DesignerOperatorBind::get('*', ['uid' => $designerUid, 'operator_id' => $id])) {
                    $errUids[] = $designerUid;
                }
            }
            if ($errUids) {
                return $this->response()->error('一键迁移失败, 这些uid不存在' . implode(',', $errUids));
            }
        }
        if (!DesignerOperatorBind::update(
            [
                'operator_id' => $toOperatorId,
                'admin_name' => $toOperatorInfo['operator_admin_name']
            ], $where)) {
            return $this->response()->error('一键迁移失败');
        }
        $logData = [
            'uid' => 0,
            'operator_id' => $toOperatorId,
            'admin_name' => $toOperatorInfo['operator_admin_name'],
            'log' => $id . '一键迁移到' . $toOperatorId . ':涉及设计师有{' . ($designerUids??'全部') . '}',
            'op_time' => date('Y-m-d H:i:s')
        ];
        DesignerOperatorBindLog::insert($logData);
        return $this->response()->success('一键迁移成功')->refresh();
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }
        return $key;
    }

    public function form()
    {
        $this->hidden('from_operator_id')->value($this->row->id);
        $this->text('to_operator_id', '迁移到运营ID')->required();
        $this->text('designer_uids', '需要迁移的设计师uid')
            ->help('请以英文逗号,分隔；若全部迁移请勿填写！');
    }
}
